/*
*    l3qd - Light, light, lightweight queue
*    Copyright (C) 2024  Marcus Pedersén marcus@marcux.org
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package sql

import (
	"fmt"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"notabug.org/marcux/l3q/internal/common"
)

// Initialize database
// and return a handle to database
func InitDb(dbPath string) (*gorm.DB, error) {
	db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
	if err != nil {
		return &gorm.DB{}, fmt.Errorf("Failed tonopen database: %s, %s", dbPath, err)
	}

	db.Exec("pragma journal_model=wal;")
	if db.Error != nil {
		return &gorm.DB{}, fmt.Errorf("Failed to set journal_model=wal, %s", db.Error)
	}

	err = db.AutoMigrate(&common.Task{})
	if err != nil {
		return &gorm.DB{}, fmt.Errorf("Failed to create table for Task, %s", err)
	}

	return db, nil
}
